package org.itboys.ace.web;

import com.alibaba.fastjson.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.entity.*;
import org.itboys.admin.service.*;
import org.itboys.admin.tools.AdminPermissionCheck;
import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.io.FileUtils;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.member.entity.Member;
import org.itboys.member.service.MemberService;
import org.itboys.mongodb.utils.page.AceJsonPageUtils;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.mongodb.utils.query.AceUtils;
import org.itboys.mongodb.utils.query.QueryParamUtils;
import org.itboys.seller.entity.Seller;
import org.itboys.seller.service.SellerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 * 
 * @author weisky
 *
 */
@RestController
@RequestMapping("/ace/admin/center")
public class AceBusinessCenterController extends BaseController {

	@Autowired
	private BusinessCenterService businessCenterService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private SellerService sellerService;
	@Autowired
	private ResourceHolder resourceHolder;

	/**
	 * 点击用户管理跳转页面
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/user-list")
	public ModelAndView listvm(HttpServletRequest request, HttpServletResponse response, Model model) {
		Map<String, Object> param = QueryParamUtils.builderQueryMap(request);
		return new ModelAndView("/ace/admin/center-list");
	}

	/**
	 * 分页查询管理用户
	 * 
	 * @return
	 */
	@RequestMapping("/list")
	public void list(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> param = QueryParamUtils.builderQueryMap(request);
		Page<BusinessCenter> page = businessCenterService.pageQuery(param, request);
		AceJsonPageUtils.renderJsonPage(page.getTotal(), page.getData(), response);
	}

	/**
	 * 异步获取单个用户对象
	 * 
	 * @param id
	 * @param response
	 */
	@RequestMapping("/getUser/{id}")
	public void getUser(@PathVariable("id") Long id, HttpServletResponse response) {
		BusinessCenter user = businessCenterService.getUserById(id);
		AjaxUtils.renderJson(response, user);
	}

	/**
	 * 异步保存
	 */
	@RequestMapping("/save")
	@AdminPermissionCheck("adminUser:save")
	public void save(
			@ModelAttribute BusinessCenter center,
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "logos", required = false) MultipartFile logos,
			@RequestParam(value = "licenseImgs", required = false) MultipartFile licenseImgs,
            @RequestParam(value = "orgImgs", required = false) MultipartFile orgImgs) {
		try {
            String logo = null;
			if (logos != null && !logos.isEmpty()) {
                logo = FileUtils.saveFile(logos.getInputStream(),
                        resourceHolder.getStringValue("fileUploadPath"),
                        logos.getOriginalFilename(), logos.getContentType());
                center.setLogo(logo);
			}
            String licImg = null;
            if(licenseImgs != null && !licenseImgs.isEmpty()){
                licImg = FileUtils.saveFile(licenseImgs.getInputStream(),
                        resourceHolder.getStringValue("fileUploadPath"),
                        licenseImgs.getOriginalFilename(), licenseImgs.getContentType());
                center.setLicenseImg(licImg);
            }
            String oImg = null;
            if(orgImgs != null && !orgImgs.isEmpty()){
                oImg = FileUtils.saveFile(orgImgs.getInputStream(),
                        resourceHolder.getStringValue("fileUploadPath"),
                        orgImgs.getOriginalFilename(), orgImgs.getContentType());
                center.setOrgImg(oImg);
            }
			if (center.getId() == 0l) {
				businessCenterService.save(center);
				// 同时保存Member
				Member member = new Member();
				member.setType(1);// 会员类型是运营中心
				member.setNickname(center.getCompanyName());
				member.setCenterId(center.getId());
				member.setLevel(0);
				member.setIsBuyer(0);
				memberService.save(member);
				member.setPath("/" + member.getId() + "/");
				memberService.update(member);
                center.setSelfMemberId(member.getId());
				businessCenterService.update(center);
				logger.info("生成运营中心虚拟会员:CTMember = " + JSON.toJSONString(member));
			} else {
                BusinessCenter oldCenter = businessCenterService.getById(center.getId());
                if(StringUtils.isBlank(logo)){
                    center.setLogo(oldCenter.getLogo());
                }
                if(StringUtils.isBlank(licImg)){
                    center.setLicenseImg(oldCenter.getLicenseImg());
                }
                if(StringUtils.isBlank(oImg)){
                    center.setOrgImg(oldCenter.getOrgImg());
                }
				businessCenterService.update(center);
			}
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("save admin user error", e);
			e.printStackTrace();
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

	/**
	 * 异步删除
	 */
	@RequestMapping("/delete/{id}")
	@AdminPermissionCheck("BusinessCenter:delete")
	public void delete(@PathVariable("id") Long id, HttpServletResponse response) {
		try {
			List<Seller> list = sellerService.findByField("centerId", id);
			if(list != null && list.size() > 0) {
				AjaxUtils.renderText(response, "-1");
			} else {
				businessCenterService.delete(id);
				AjaxUtils.renderText(response, CommonConstants.SUCCESS);
			}
		} catch (Exception e) {
			logger.error(" BusinessCenter delete error", e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}
	
	/**
	 * 异步删除LOGO
	 */
	@RequestMapping("/deleteImage/{id}")
	@AdminPermissionCheck("deleteImage")
	public void deleteImage(@PathVariable("id") Long id, HttpServletResponse response) {
		try {
			BusinessCenter adminUser = businessCenterService.getById(id);
			//adminUser.setBigLogo("");
			businessCenterService.update(adminUser);
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("BusinessCenter deleteImage error", e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

	@RequestMapping("/simpleUpdate")
	public void simpleSave(@ModelAttribute BusinessCenter BusinessCenter,
			HttpServletResponse response,
			@RequestParam("logos") MultipartFile logos) {
		try {
			if (logos != null && !logos.isEmpty()) {
				String filePath = FileUtils.saveFile(logos.getInputStream(), resourceHolder.getStringValue("fileUploadPath"), logos.getOriginalFilename(), logos.getContentType());
				//BusinessCenter.setBigLogo(filePath);
			}
			if (BusinessCenter.getId() == 0l) {
				//BusinessCenter.setPassword(Digests.md5(BusinessCenter.getPassword()));
				businessCenterService.save(BusinessCenter);
			} else {
				BusinessCenter user = businessCenterService.getById(BusinessCenter.getId());
                user.setCr(user.getCr());
                user.setCt(user.getCt());
                //user.setPassword(user.getPassword());
                user.setUr(AdminSessionHolder.getAdminUserId());
                user.setUt(System.currentTimeMillis());
				businessCenterService.update(BusinessCenter);
			}

			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("simpleSave Admin user error", e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}

}
